<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <el-button @click="back" icon="el-icon-arrow-left">返回</el-button>
        <span style="margin-left: 10px">{{
          ruleForm.id ? ($route.query.type == 1 ? '编辑课件' : '预览课件') : '新增课件'
        }}</span>
      </div>
      <el-form
        :model="ruleForm"
        style="width: 100%"
        :rules="rules"
        ref="ruleForm"
        label-width="90px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训类型" prop="selected_type_ids">
              <el-cascader
                :show-all-levels="false"
                :options="options2"
                style="width: 100%"
                v-model="ruleForm.selected_type_ids"
                :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
                :disabled="$route.query.type == 2"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课件名称" prop="title">
              <el-input
                :disabled="$route.query.type == 2"
                v-model="ruleForm.title"
                maxlength="50"
                show-word-limit
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课件时长" prop="duration">
              <div class="flex">
                <el-input-number
                  controls-position="right"
                  class="input_number"
                  v-model="ruleForm.duration"
                  :step="1"
                  :precision="0"
                  :min="1"
                  :disabled="$route.query.type == 2"
                ></el-input-number>
                <span style="flex-shrink: 0; margin-left: 10px; font-size: 12px">分钟</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学时" prop="hour">
              <el-input :disabled="$route.query.type == 2" v-model="ruleForm.hour" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联教师" prop="teacher_id">
              <div class="flex">
                <el-select
                  :disabled="$route.query.type == 2"
                  style="width: 100%"
                  filterable
                  v-model="ruleForm.teacher_id"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in teacherList"
                    :key="index"
                    :label="item.username"
                    :value="item.id"
                    >{{ item.username || '' }}</el-option
                  >
                </el-select>
                <el-button
                  v-if="$route.query.type != 2"
                  type="primary"
                  size="mini"
                  style="flex-shrink: 0; margin-left: 10px"
                  @click="handleAddTearch"
                  >新增讲师</el-button
                >
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开启练习题" prop="topic_open">
              <el-radio-group  v-model="ruleForm.topic_open">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="2">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传课件" prop="video_url">
              <el-upload
                v-if="$route.query.type != 2"
                action="#"
                :show-file-list="false"
                accept=".mp4"
                :http-request="handleUploadVideo">
              <el-button type="primary">上传本地视频</el-button>
              </el-upload>

               <p v-if="fileName && $route.query.type != 2">{{ fileName }}</p>
<!--              <video-->
<!--                v-if="ruleForm.video_url"-->
<!--                class="video-style"-->
<!--                controls-->
<!--                :src="ruleForm.video_url"-->
<!--              ></video>-->
                <template v-if="ruleForm.video_url"><div>
                <video-player
                  :options="playerOptions"
                  playsinline
                >
                </video-player>
                </div></template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课件封面" prop="img_url">
              <p class="prompt">建议上传尺寸225*160，格式JPG、PNG、JPEG</p>
              <el-upload
                v-if="$route.query.type != 2"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                accept=".jpg, .png, .jpeg"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarSuccess"
              >
                <img v-if="ruleForm.img_url" :src="ruleForm.img_url" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-image
                style="width: 150px; height: 106px"
                v-if="$route.query.type == 2 && ruleForm.img_url"
                :src="ruleForm.img_url"
                :preview-src-list="[ruleForm.img_url]"
                class="avatar"
              >
              </el-image>
            </el-form-item>
          </el-col>
        </el-row>
        <br>
        <el-form-item label="课后习题" prop="topic_ids" >
          <el-button
            v-if="$route.query.type != 2"
            type="primary"
            size="mini"
            style="flex-shrink: 0; margin-left: 10px"
            @click="addTest"
            >添加</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="tableData"
        border
        ref="tip"
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        style="width: 100%; margin-bottom: 60px"
      >
        <el-table-column fixed type="index" align="center" label="序号" width="50" />
        <el-table-column fixed prop="title" align="center" show-overflow-tooltip label="题目内容" min-width="240" />
        <el-table-column prop="type" align="center" label="题目类型" width="140">
          <template #default="scope">
            {{ scope.row.type | getType }}
          </template>
        </el-table-column>
        <el-table-column
          prop="options"
          align="center"
          show-overflow-tooltip
          label="题目选项"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="answer" align="center" label="题目答案" width="140"></el-table-column>
        <el-table-column prop="resource_type" align="center" label="课件来源" min-width="100">
          <template #default="scope">
            <span v-if="scope.row.resource_type == 1">公共资源</span>
            <span v-else-if="scope.row.resource_type == 2">平台资源</span>
            <span v-else-if="scope.row.resource_type == 3">我的资源</span>
          </template>
        </el-table-column>
        <el-table-column prop="type_name" align="center" label="培训类型" width="140"> </el-table-column>
        <el-table-column
          v-if="$route.query.type != 2"
          fixed="right"
          align="center"
          prop="action"
          label="操作"
          width="160"
        >
          <template #default="scope">
            <div class="action">
              <span v-if="scope.$index != 0" @click="handleUp(scope)">上移</span>
              <span v-if="scope.$index != tableData.length - 1" @click="handleDown(scope)">下移</span>
              <span @click="delOk(scope)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="footer" v-if="$route.query.type != 2">
      <el-button @click="back">关闭</el-button>
      <el-button type="primary" size="medium" @click="submitForm('ruleForm')">确认</el-button>
    </div>

    <!-- 选择试题 -->
    <el-dialog title="选择试题" :visible.sync="isShowAdd2" width="1200px" :before-close="handleClose2" :close-on-click-modal="false">
      <div class="head">
        <div class="input">
          <span>题目名称：</span>
          <el-input v-model="queryData2.title" placeholder="请输入" />
        </div>
        <div class="input">
          <span>题目类型：</span>
          <el-select v-model="queryData2.type" placeholder="请选择题目类型">
            <el-option label="单选" :value="1">单选</el-option>
            <el-option label="多选" :value="2">多选</el-option>
            <el-option label="判断" :value="3">判断</el-option>
          </el-select>
        </div>
        <div class="input">
          <span>培训类型：</span>
          <el-cascader
            :show-all-levels="false"
            :options="options2"
            v-model="queryData2.selected_type_ids"
            :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
            clearable
          ></el-cascader>
        </div>
        <div class="input" v-if="this.$route.query.resource_type == 3">
          <span>课程来源：</span>
          <el-select v-model="queryData2.resource_type" placeholder="请选择课件来源">
            <el-option label="公共课件" :value="1">公共课件</el-option>
            <el-option label="平台课件" :value="2">平台课件</el-option>
            <el-option label="我的课件" :value="3">我的课件</el-option>
          </el-select>
        </div>
        <el-button type="primary" class="btn" @click="search2">查询</el-button>
        <el-button type="primary" class="btn" @click="reset2">重置</el-button>
      </div>
      <el-table
        :data="tableData2"
        border
        v-loading="isTableLoading"
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column fixed type="selection" align="center" label="序号" width="50" />
        <el-table-column fixed prop="title" align="center" show-overflow-tooltip label="题目内容" min-width="240" />
        <el-table-column prop="type" align="center" label="题目类型" width="140">
          <template #default="scope">
            {{ scope.row.type | getType }}
          </template>
        </el-table-column>
        <el-table-column
          prop="options"
          align="center"
          show-overflow-tooltip
          label="题目选项"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="answer" align="center" label="题目答案" width="140"></el-table-column>
        <el-table-column prop="resource_type" align="center" label="课件来源" min-width="100">
          <template #default="scope">
            <span v-if="scope.row.resource_type == 1">公共资源</span>
            <span v-else-if="scope.row.resource_type == 2">平台资源</span>
            <span v-else-if="scope.row.resource_type == 3">我的资源</span>
          </template>
        </el-table-column>
        <el-table-column prop="type_name" align="center" label="培训类型" width="140"> </el-table-column>
      </el-table>
      <el-pagination
        background
        style="margin-top: 5px; text-align: right"
        @size-change="search2"
        @current-change="getTopicList"
        :current-page.sync="queryData2.page"
        :page-size.sync="queryData2.size"
        layout="total, prev, pager, next,sizes,jumper"
        :total="total2"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">关闭</el-button>
        <el-button type="primary" @click="handleConfirmSelectTopic">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { TrainTypeTree, TeacherListAll, upload, TopicList, CoursewareSave, CoursewareInfo } from '@/api/manage';
import { videoPlayer } from 'vue-video-player';
import 'videojs-contrib-hls';
import 'video.js/dist/video-js.css'
import axios from "axios";

export default {
  name: 'addCourseware',
  components: { videoPlayer },
  data() {
    return {
      ruleForm: {
        title: '',
        type_ids: [],
        selected_type_ids: [],
        duration: null,
        hour: '',
        teacher_id: '',
        video_url: '',
        img_url: '',
        topic_ids: [],
        topic_open:2
      },
      rules: {
        title: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        hour: [{ required: true, message: '请输入学时', trigger: 'blur' }],
        selected_type_ids: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
        duration: [{ required: true, message: '请输入课件时长', trigger: 'blur' }],
        // teacher_id: [{ required: true, message: '请选择关联讲师', trigger: 'change' }],
        video_url: [{ required: true, message: '请上传课件', trigger: 'change' }],
        topic_open:[{ required: true, message: '请选择是否开启练习题', trigger: 'change' }],
      },
      isShowAdd: false,
      addData: {},
      options2: [],
      total: 0,
      queryData2: {
        page: 1,
        size: 10,
        type: '',
        title: '',
        create_type: this.$route.query.create_type,
        resource_type: 3,
      },
      tableData2: [],
      total2: 0,
      isTableLoading: false,
      tableData: [],
      isShowAdd2: false,
      queryData: {
        name: '',
        type: [],
        page: 1,
        size: 5,
      },
      teacherList: [],
      fileName: '',
      topic_ids: [],
      playerOptions: {
        // fluid: true, // 响应式布局
        controls: true, // 显示控制条
        autoplay: false, // 自动播放
        controlBar: {
          progressControl: true,  // 显示进度条控件
          fullscreenToggle: false  // 显示全屏按钮
        },
        sources: [{
          src: '',  // 视频地址
          type: 'application/x-mpegURL'  // HLS 格式标识:ml-citation{ref="4" data="citationList"}
        }],
        width: 400,
        height: 283,
      }
    };
  },
  filters: {
    getType(type) {
      switch (type) {
        case 1:
          return '单选';
        case 2:
          return '多选';
        case 3:
          return '判断';
        default:
          return '';
      }
    },
  },
  computed: {},
  created() {
    this.getTrainTypeTree();
    this.getTeacherListAll();
    if (this.$route.query.id) {
      this.getInfo();
    }
  },
  mounted() {},
  watch: {
    'ruleForm.video_url' : {
      handler(val) {
        // 给视频赋值
        this.playerOptions.sources[0].src = val;
      }
    },
    'ruleForm.selected_type_ids': {
      handler(val) {
        this.ruleForm.type_ids = val.map((item) => item[item.length - 1]);
      },
      deep: true,
    },
    tableData: {
      handler(val) {
        // this.ruleForm.topic_ids = val.map(item => item.id).join(',');
        this.ruleForm.topic_ids = val.map((item) => item.id);
      },
      deep: true,
    },
  },
  methods: {
    handleUp(scope) {
      if (scope.$index <= 0) return;
      this.tableData = [
        ...this.tableData.slice(0, scope.$index - 1),
        this.tableData[scope.$index],
        this.tableData[scope.$index - 1],
        ...this.tableData.slice(scope.$index + 1),
      ];
    },
    handleDown(scope) {
      if (scope.$index >= this.tableData.length - 1) return;
      this.tableData = [
        ...this.tableData.slice(0, scope.$index),
        this.tableData[scope.$index + 1],
        this.tableData[scope.$index],
        ...this.tableData.slice(scope.$index + 2),
      ];
    },
    delOk(scope) {
      this.$confirm('确定删除该试题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.tableData.splice(scope.$index, 1);
      });
    },
    getInfo() {
      CoursewareInfo({
        id: this.$route.query.id,
      }).then((res) => {
        this.ruleForm = JSON.parse(JSON.stringify(res.data.data));
        this.fileName = this.ruleForm.video_url.split('/').pop();
        if (this.ruleForm.topic_ids?.length) {
          this.getTopicInfo();
        }
      });
    },
    handleConfirmSelectTopic() {
      if (!this.topic_ids.length) {
        this.$message.error('请选择试题');
        return;
      }
      this.tableData = this.topic_ids.concat(this.tableData);
      this.handleClose2();
    },
    reset2() {
      this.queryData2 = {
        page: 1,
        size: 10,
        type: '',
        title: '',
        exclude_ids: [],
        create_type: this.$route.query.create_type,
      };
      this.getTopicList();
    },
    search2() {
      this.queryData2.page = 1;
      this.getTopicList();
    },
    handleSelectionChange(val) {
      this.topic_ids = val;
    },
    handleClose2() {
      this.isShowAdd2 = false;
      this.queryData2 = {
        page: 1,
        size: 10,
        type: '',
        title: '',
        create_type: this.$route.query.create_type,
      };
    },
    async handleUploadVideo(e) {
      // 调用第三方接口, 返回m3u8格式视频

      let obj = new FormData();
      obj.append('file', e.file);
      try {
        const response = await axios.post(
          'https://shipina.anshangwang.com/merchant/Test/shipin2',
          obj,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
        // 处理成功响应
          this.ruleForm.video_url = response.data.data;
          this.$message.success('上传成功');
          this.fileName = e.file.name;
      } catch (error) {
        // 处理错误
        this.errorMessage = '提交失败，请检查网络或参数';
        console.error("调用接口时出错:", error);
      }

      // 老版本上传
      // let obj = new FormData();
      // obj.append('file', e.file);
      // upload(obj).then((res) => {
      //   this.ruleForm.video_url = res.data.url;
      //   this.$message.success('上传成功');
      //   this.fileName = e.file.name;
      // });
    },
    handleAddTearch() {
      this.$router.push({
        path: '/company/addTeacher/index',
        query: { create_type: this.$route.query.create_type },
      });
    },
    search() {
      this.queryData.page = 1;
      this.getTopicList();
    },
    reset() {
      this.queryData.title = '';
      this.queryData.type = '';
      this.queryData.type2 = [];
      this.search();
    },
    addTest() {
      this.queryData2.exclude_ids = this.ruleForm.topic_ids || [];
      this.getTopicList();
      this.isShowAdd2 = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.create_type = this.$route.query.create_type;
          this.ruleForm.resource_type = this.$route.query.resource_type ?? ''; // 1是公共资源
          CoursewareSave(this.ruleForm).then((res) => {
            this.$message.success(this.ruleForm.id ? '修改成功' : '添加成功');
            this.back();
          });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    },
    handleAvatarSuccess(e) {
      let obj = new FormData();
      obj.append('file', e.file);
      upload(obj).then((res) => {
        this.ruleForm.img_url = res.data.url;
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    getTopicList() {
      this.isTableLoading = true;
      this.queryData2.id = this.$route.query.id;
      let resource_type = this.$route.query.resource_type;
      if ( resource_type != 3 ) {
        this.queryData2.resource_type = resource_type;
      }
      TopicList(this.queryData2).then((res) => {
        this.tableData2 = res.data.list;
        this.total2 = res.data.total;
        this.isTableLoading = false;
      });
    },
    getTopicInfo() {
      TopicList({
        id:this.$route.query.id,
        ids: this.ruleForm.topic_ids,
        create_type: this.$route.query.create_type,
        page: 1,
        size: this.ruleForm.topic_ids.length,
      }).then((res) => {
        this.tableData = res.data.list;
      });
    },
    getTrainTypeTree() {
      TrainTypeTree().then((res) => {
        this.options2 = res.data.list;
      });
    },
    getTeacherListAll(val) {
      TeacherListAll({
        create_type: 2,
        username: val,
      }).then((res) => {
        this.teacherList = res.data.list;
      });
    },
    back() {
      this.$router.back();
    },
  },
};
</script>

<style scoped>
.flex {
  display: flex;
  align-items: center;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 106px;
  display: flex;
  align-items: center;
}
.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  line-height: 106px;
  text-align: center;
}
.avatar {
  width: 100%;
  display: block;
}
.prompt {
  font-size: 12px;
  color: #8c939d;
  margin-bottom: 5px;
}
.input_number {
  width: 100%;
  text-align: center;
}
.demo-ruleForm /deep/ .el-input-number__decrease,
.demo-ruleForm /deep/ .el-input-number__increase {
  display: block !important;
}

.footer {
  width: 100%;
  height: 60px;
  position: fixed;
  bottom: 0px;
  left: 0;
  z-index: 9;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 210px;
  border-top: 1px solid #e6e6e6;
}
.head {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  background: #ffffff;
  border-radius: 5px;
}
.input {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 20px;
}
.input > span {
  font-size: 12px;
  flex-shrink: 0;
}
.btn {
  margin-bottom: 20px;
}
.video-style {
  width: 400px;
  height: 283px;
}
.action {
  display: flex;
  align-items: center;
  justify-content: center;
}
.action span,
.look {
  color: #0256ff;
  font-size: 12px;
  cursor: pointer;
  margin: 0 8px;
}
::v-deep .vjs-tech {
  width: 400px;
  height: 283px;
}
/* 使用深度选择器穿透作用域 */
/*
::v-deep .vjs-loading-spinner,
::v-deep .vjs-big-play-button,
::v-deep .vjs-error-display,
::v-deep .vjs-text-track-settings,
::v-deep .vjs-control-bar,
::v-deep .vjs-time-controls,
::v-deep .vjs-duration-display,
::v-deep .vjs-current-time-display,
::v-deep .vjs-remaining-time-display,
::v-deep .vjs-progress-control,
::v-deep .vjs-volume-panel,
::v-deep .vjs-mute-toggle,
::v-deep .vjs-fullscreen-control {
  display: none !important;
}

 */
</style>
